const Account = require("../models/accounts")
class AccountCtrl {

    async checkAccountExist(ctx) {
        const account = await Account.findById(ctx.params.id)
        if (!account) {
            ctx.throw(404, '账单不存在')
        }
    }

    async find(ctx) {
        let { per_page = 2, q = '' } = ctx.query
        let page = Math.max(ctx.query.page * 1, 1) - 1
        let perPage = Math.max(per_page * 1, 1)
        ctx.body = Account
            .find({ name: new RegExp(q), gender: q })
            .limit(perPage)
            .skip(page * perPage)
    }

    async findById(ctx) {
        const { fields = '' } = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => '+' + f).join(' ')
        const account = await Account.findById(ctx.params.id).select(selectFields)
        ctx.body = account
    }

    async create(ctx) {
        ctx.verifyParams({
            title: {
                type: 'string',
                required: true
            },
            type: {
                type: 'string',
                required: true
            },
            remark: {
                type: 'string',
                required: false
            },
            purpose: {
                type: 'string',
                required: true
            },
        })
        const { name } = ctx.request.body
        const repeatedAccount = await Account.findOne({ name })
        if (repeatedAccount) {
            ctx.throw(409, '账单已存在')
        }
        const account = await new Account(ctx.request.body).save()
        ctx.body = account
    }

    async update(ctx) {
        ctx.verifyParams({
            title: {
                type: 'string',
                required: false
            },
            type: {
                type: 'string',
                required: false
            },
            remark: {
                type: 'string',
                required: false
            },
            purpose: {
                type: 'string',
                required: false
            },
        })
        const account = await Account.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = account
    }

    async delete(ctx) {
        await Account.findByIdAndDelete(ctx.params.id, ctx.request.body)
        ctx.status = 204
    }
    async findJson(ctx) {
        let x = { 1: 2, 3: 4 }
        x[-2] = 3
        ctx.body = x
    }
}

module.exports = new AccountCtrl()